from django.contrib import admin
from .models import SKU
from django.core.cache import caches

GOODS_INDEX_CACHE = caches["goods_index"]
GOODS_DETAIL_CACHE = caches['goods_detail']

@admin.register(SKU)
class SKUAdmin(admin.ModelAdmin):
    # 修改操作，重写ModelAdmin中的save_model()方法
    def save_model(self, request, obj, form, change):
        # 执行父类方法：更新mysql数据
        super().save_model(request, obj, form, change)
        # 清除redis缓存
        GOODS_INDEX_CACHE.clear()
        print("首页数据更新，缓存清除")
        # 清除详情页缓存
        key = f'gd{obj.id}'
        GOODS_DETAIL_CACHE.delete(key)
        print("数据更新， 详情页缓存清除")

    # 删除操作
    def delete_view(self, request, object_id, extra_context=None):
        # 执行父类方法：更新mysql数据
        super().delete_view(request, object_id)
        # 清除redis缓存
        GOODS_INDEX_CACHE.clear()
        print("首页数据更新，缓存清除")

# admin.site.register(SKU, SKUAdmin)


